/*
 * Copyright (C) 2012 attmore
 * e-mail: attmore@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pocketsweet.ui.uilib;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.ui.Main;

/**
 * @author attmore
 * 
 */
public class RecordButtonView extends LinearLayout implements
		View.OnClickListener {
	private Context _ctx;
	private MediaRecorder mMediaRecorder;
	private MediaPlayer mMediaPlayer;
	private String mRecordPath = C.CACHE_FILE + "/record.amr";
	private ImageButton btnMain, btnDelete;
	private TextView tvTime;
	private int status = STATUS_NORMAL;
	private int time;
	private static final int STATUS_NORMAL = 0x01;
	private static final int STATUS_RECORDING = 0x02;
	private static final int STATUS_RECORDED = 0x03;
	private static final int STATUS_PLAYING = 0x04;

	private static final int MSG_RECORD = 0x01;
	private static final int MSG_STOP = 0x02;
	private static final int MSG_PLAY = 0x03;
	private static final int MSG_PAUSE = 0x04;
	private static final int MSG_UPDATE_TIME = 0x05;
	private static final int MSG_RESET = 0x06;

	public RecordButtonView(Context context, AttributeSet attrs) {
		super(context, attrs);
		_ctx = context;
		initView();
	}

	private void initView() {
		View root = inflate(_ctx, R.layout.view_record_button, null);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		addView(root, params);
		btnMain = (ImageButton) root.findViewById(R.id.record_btn);
		btnDelete = (ImageButton) root.findViewById(R.id.record_del_btn);
		btnMain.setOnClickListener(this);
		btnDelete.setOnClickListener(this);
		tvTime = (TextView) root.findViewById(R.id.record_timer);
		tvTime.setText("点击录音");
	}

	private Handler mRecordHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_RECORD:
				try {
					mMediaRecorder.start();
				} catch (IllegalStateException e) {
//					Log.e("errorrr", e.getMessage().toString() + " ");
					e.printStackTrace();
				}
				btnMain.setImageResource(R.drawable.icon_stop);
				tvTime.setVisibility(View.VISIBLE);
				mRecordHandler.sendEmptyMessage(MSG_UPDATE_TIME);
				status = STATUS_RECORDING;
				break;
			case MSG_STOP:
				if (mMediaRecorder != null) {
					mMediaRecorder.stop();
					mMediaRecorder.reset();
					mMediaRecorder.release();
					mMediaRecorder = null;
				}
				btnMain.setImageResource(R.drawable.icon_play);
				btnDelete.setVisibility(View.VISIBLE);
				status = STATUS_RECORDED;
				mRecordHandler.removeMessages(MSG_UPDATE_TIME);
				break;
			case MSG_PLAY:
				// if (mMediaPlayer == null) {
				mMediaPlayer = new MediaPlayer();
				// }
				mMediaPlayer
						.setOnCompletionListener(new OnCompletionListener() {
							@Override
							public void onCompletion(MediaPlayer mp) {
								mMediaPlayer.stop();
								btnMain.setImageResource(R.drawable.icon_play);
								status = STATUS_RECORDED;
							}
						});
				try {
					mMediaPlayer.setDataSource(mRecordPath);
					mMediaPlayer.prepare();
					mMediaPlayer.start();
				} catch (IOException e) {
				}
				status = STATUS_PLAYING;
				btnMain.setImageResource(R.drawable.icon_pause);
				break;
			case MSG_PAUSE:
				mMediaPlayer.stop();
				btnMain.setImageResource(R.drawable.icon_play);
				status = STATUS_RECORDED;
				break;
			case MSG_UPDATE_TIME:
				if (time < 120) {
					tvTime.setText((time++) + "/120s");
					mRecordHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME,
							1000);
				} else {
					mRecordHandler.sendEmptyMessage(MSG_STOP);
				}
				break;
			case MSG_RESET:
				if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
				}
				if (mMediaPlayer != null) {
					mMediaPlayer.reset();
				}
				status = STATUS_NORMAL;
				btnMain.setImageResource(R.drawable.icon_record_normal);
				btnDelete.setVisibility(View.INVISIBLE);
				time = 0;
				// tvTime.setVisibility(View.INVISIBLE);
				tvTime.setText("点击录音");
				break;
			}
		}

	};

	public ArrayList<String> getSoundPath() {
		ArrayList<String> list = new ArrayList<String>();
		list.addAll(Arrays.asList(mRecordPath));
		return list;
	}

	public boolean isRecorded() {
		return status == STATUS_RECORDED ? true : false;
	}

	public boolean isRecording() {
		return status == STATUS_RECORDING ? true : false;
	}

	public void destoryRecord() {
		if (isRecording()) {
			mMediaRecorder.stop();
			mMediaRecorder.reset();
			mMediaRecorder.release();
			mMediaRecorder = null;
		}
		if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
			mMediaPlayer.pause();
			mMediaPlayer.stop();
			mMediaPlayer.reset();
		}
	}

	private class LoadingThread extends Thread {
		@Override
		public void run() {
			super.run();
			mMediaRecorder = new MediaRecorder();
			mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
			mMediaRecorder.setAudioSamplingRate(8000);
			mMediaRecorder.setOutputFile(mRecordPath);
			mMediaRecorder.setAudioChannels(1);
			mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			try {
				mMediaRecorder.prepare();
			} catch (IOException e) {
				e.printStackTrace();
			}
			mRecordHandler.sendEmptyMessage(MSG_RECORD);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.record_btn:
			if (status == STATUS_NORMAL) {
				LoadingThread tmpThread = new LoadingThread();
				tmpThread.start();
			}
			if (status == STATUS_RECORDING) {
				mRecordHandler.sendEmptyMessage(MSG_STOP);
			}
			if (status == STATUS_RECORDED) {
				mRecordHandler.sendEmptyMessage(MSG_PLAY);
			}
			if (status == STATUS_PLAYING) {
				mRecordHandler.sendEmptyMessage(MSG_PAUSE);
			}
			break;
		case R.id.record_del_btn:
			mRecordHandler.sendEmptyMessage(MSG_RESET);
			break;
		}
	}

	public void setVoicePath(String sPath) {
		if (sPath == null || sPath.equals("")) {
			return;
		}
		mRecordPath = sPath;
		status = STATUS_RECORDED;
		btnMain.setImageResource(R.drawable.icon_play);
		btnDelete.setVisibility(View.VISIBLE);
		status = STATUS_RECORDED;
	}

	public int getTime() {
		return time;
	}

	// private class SoundApmUpdater extends TimerTask {
	// @Override
	// public void run() {
	// int vuSize = 60 * mMediaRecorder.getMaxAmplitude() / 32768;
	// Message mUpdate = mRecordHandler.obtainMessage();
	// mUpdate.what = MSG_UPDATE_TIME;
	// mUpdate.arg1 = vuSize;
	// mRecordHandler.sendMessage(mUpdate);
	// }
	// }

}
